# $Id: chat.py 14 2008-08-21 21:31:25Z jkingry $

import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson

mithril_service_url = "http://192.168.1.43:8080/service/"
chat_service_url = "http://192.168.1.43:8080/chat/"

def generate_string(length=16):
  import string
  import random
  d = [random.choice(string.letters + string.digits) for x in xrange(length)]
  s = "".join(d)
  return s

def new_account_key():
    return 'ChatAccount_' + generate_string()
    
def current_account():
    user = users.get_current_user()
    
    account = ChatAccount.all().filter("user =", user).get()
      
    if account is None:
      account = ChatAccount(key_name = new_account_key(), user = user)
      db.put(account)    
	  
    return account
    
class ChatAccount(db.Model):
  user = db.UserProperty(required = True)
  created = db.DateTimeProperty(auto_now_add = True)
  rooms = db.ListProperty(db.Key)  
  
class ChatRoom(db.Model):
    name = db.StringProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)
    owner = db.ReferenceProperty(ChatAccount, required = True)
    ip_address = db.StringProperty()
    channel = db.BlobProperty()
    
    @property
    def members(self):
        return Account.gql("WHERE rooms = :1", self.key()) 

class ChatRoomMember(db.Model):
    room = db.ReferenceProperty(ChatRoom, required = True)
    Account = db.ReferenceProperty(ChatAccount, required = True)
    connected = db.BooleanProperty(default = True)
    
class ChatMessage(db.Model):
    room = db.ReferenceProperty(ChatRoom, required = True)
    sender = db.ReferenceProperty(ChatAccount, required = True)
    message = db.StringProperty()
    created = db.DateTimeProperty(auto_now_add = True)
 	
class ChatDefaultHandler(webapp.RequestHandler):
  def get(self): 
    template_values = {
      'account': current_account(),
      'chat_service_url': chat_service_url,
      'mithril_service_url': mithril_service_url,
      'logout_url': users.create_logout_url("/chat")
    }
    
    path = os.path.join(os.path.dirname(__file__), 'chat.html')
    self.response.out.write(template.render(path, template_values))

class BaseHandler(webapp.RequestHandler):
    def __init__(self):
        self.load_account = True
    def get(self):
        try:
            if self.load_account:	 
                account_key = self.request.get('account')
                account = db.get(account_key)
            
                if account is None:
                    raise ApplicationError, "Invalid account"     
            
            result = self.run(account)
            self.response.out.write(simplejson.dumps(result))
        except ApplicationError, x:
            self.set_status(500, str(x))        
        
    def run(self, account):
        pass

class ChatCreateHandler(BaseHandler):
    def run(self, account):     
        name = self.request.get('name')
        
        room = ChatRoom(name = name, owner = account)
        db.put(room)
        
        return {
            'room_key': str(room.key())
            }

class ChatUpdateHandler(BaseHandler):
    def run(self, account):     
        pass

class ChatListHandler(BaseHandler):
    def run(self, account):     
        pass

class ChatDeleteHandler(BaseHandler):
    def run(self, account):     
        pass

application = webapp.WSGIApplication(
                                     [
                                      ('/chat/list', ChatListHandler),
                                      ('/chat/create', ChatCreateHandler),
                                      ('/chat/update', ChatUpdateHandler),
                                      ('/chat/delete', ChatDeleteHandler),
                                      ('/chat', ChatDefaultHandler),
                                     ],
                                     debug=True)        
def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()